<template>
    <view class="rx-date">
        <div v-if="readOnly" class="rx-disabled">{{ getCurrentValue()}}</div>
        <div v-else class="rx-date-select">
            <span class="rx-date-name" :style="[value?'color: #555555':'color:#ccc']" @click="showPlugin">{{ getCurrentValue()}}</span>
            <my-icon class="rx-date-icon" @click="onAllowClear" :type="value?'icon-lineicon-test28':'icon-lineVue3_date'"></my-icon>
        </div>
        <lingfeng-timepicker ref="date" :type="dateMode" :defaultData="defaultData" :maxDate="maxDate"
                             :minDate="minDate" @change="confirm"></lingfeng-timepicker>
    </view>
</template>

<script>
/*
日期控件
https://ext.dcloud.net.cn/plugin?id=11492
 */
import MForm from '../js/MForm';
import dayjs from 'dayjs';
import weekOfYear from 'dayjs/plugin/weekOfYear';
import advancedFormat from 'dayjs/plugin/advancedFormat';
import Util from "@/js/Util.js"

export default {
    name: "MDate",
    mixins: [MForm],
    data() {
        return {
            dateMode: 'date',
            params: {},
            defaultData: {
                year: "",
                month: "",
                startTime: "",
                week: "",
                quarter: ""
            },
        }
    },
    computed: {
        maxDate() {
            let conf = this.metadata.options;
            let maxDate = {};
            if (conf.relate && conf.relate != 'none') {
                if (['today', 'field'].includes(conf.relate)) {
                    let dateObj;
                    if (conf.relate == 'field') {
                        let compareDate = this.data[conf.relateField];
                        if (!compareDate) {
                            maxDate.year = dayjs().year() + 10;
                            return maxDate;
                        }
                        dateObj = dayjs(compareDate);
                    } else {
                        dateObj = dayjs();
                    }
                    let year = dateObj.year();
                    let month = dateObj.month() + 1;
                    let date = dateObj.date()
                    let hour = dateObj.hour()
                    let minute = dateObj.minute()
                    let second = dateObj.second()
                    if (conf.compare == 'gt') {
                        //大于
                        maxDate = {
                            year: year,
                            month: month,
                            date: date,
                            hour: hour,
                            minute: minute,
                            second: second,
                        }
                    } else if (conf.compare == 'ge') {
                        //大于等于
                        maxDate = {
                            year: year,
                            month: month,
                            date: Object.keys(this.params).length == 0 ? date - 1 : date,
                            hour: hour,
                            minute: this.params.second ? minute : minute - 1,
                            second: this.params.second ? second - 1 : second,
                        }
                    } else {
                        maxDate.year = dayjs().year() + 10;
                    }
                } else if (conf.relate == 'script') {
                    if (this.formVm[conf.script]) {
                        let result = this.formVm[conf.script](null, dayjs, 'mobile');
                        if (result) {
                            maxDate = result.maxDate || {};
                        }
                    }
                }
            } else {
                maxDate.year = dayjs().year() + 10;
            }
            return maxDate;
        },
        minDate() {
            let conf = this.metadata.options;
            let minDate = {};
            if (conf.relate && conf.relate != 'none') {
                if (['today', 'field'].includes(conf.relate)) {
                    let dateObj;
                    if (conf.relate == 'field') {
                        let compareDate = this.data[conf.relateField];
                        if (!compareDate) {
                            return;
                        }
                        dateObj = dayjs(compareDate);
                    } else {
                        dateObj = dayjs();
                    }
                    let year = dateObj.year();
                    let month = dateObj.month() + 1;
                    let date = dateObj.date()
                    let hour = dateObj.hour()
                    let minute = dateObj.minute()
                    let second = dateObj.second()
                    if (conf.compare == 'lt') {
                        //小于
                        minDate = {
                            year: year,
                            month: month,
                            date: date,
                            hour: hour,
                            minute: minute,
                            second: second,
                        }
                    } else if (conf.compare == 'le') {
                        //小于等于
                        minDate = {
                            year: year,
                            month: month,
                            date: Object.keys(this.params).length == 0 ? date + 1 : date,
                            hour: hour,
                            minute: this.params.second ? minute : minute + 1,
                            second: this.params.second ? second + 1 : second,
                        }
                    }
                } else if (conf.relate == 'script') {
                    if (this.formVm[conf.script]) {
                        let result = this.formVm[conf.script](null, dayjs, 'mobile');
                        if (result) {
                            minDate = result.minDate || {};
                        }
                    }
                }
            }
            return minDate;
        }
    },
    created() {
        dayjs.extend(advancedFormat);
        dayjs.extend(weekOfYear);
        this.init();
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"componentsLang",key);
        },
        getCurrentValue() {
            let value
            if(this.readOnly){
                value= ''
            }else {
                value = this.i18n('select', "请选择")
            }
            if (["year"].includes(this.dateMode)) {
                value = this.defaultData.year || value;
            } else if (["year-month"].includes(this.dateMode)) {
                value = this.defaultData.month || value;
            } else if (["week"].includes(this.dateMode)) {
                value = this.defaultData.week || value;
            } else if (["quarter"].includes(this.dateMode)) {
                value = this.defaultData.quarter || value;
            } else if (!["year", "year-month", "quarter"].includes(this.dateMode)) {
                value = this.defaultData.startTime || value;
            }
            return value
        },
        showPlugin() {
            this.$refs.date.show();
        },
        initDate(format, conf) {
            if (format == 'YYYY-MM-DD HH:mm:ss') {
                this.dateMode = 'datetime-all';
                this.params.hour = true;
                this.params.minute = true;
                this.params.second = true;
            } else if (format == 'YYYY/MM/DD HH:mm:ss') {
                this.dateMode = 'datetime-all';
                this.params.hour = true;
                this.params.minute = true;
                this.params.second = true;
            } else if (format == 'YYYY-MM-DD HH:mm') {
                this.dateMode = 'datetime';
                this.params.hour = true;
                this.params.minute = true;
            } else if (format == 'YYYY/MM/DD HH:mm') {
                this.dateMode = 'datetime';
                this.params.hour = true;
                this.params.minute = true;
            } else if (format == 'YYYY/MM/DD') {
                // 只是年月日
                this.dateMode = 'date';
            } else {
                // 只是年月日
                this.dateMode = 'date';
            }
        },
        init() {
            let conf = this.metadata.options;
            let format = conf.format;
            let curValue = this.value;
            if (conf.ctlType == 'date') {
                this.initDate(format, conf);
            } else if (conf.ctlType == 'month' ) {
                this.dateMode = 'year-month';
            } else if (conf.ctlType == 'year') {
                this.dateMode = 'year';
            } else if (conf.ctlType == 'week') {
                this.dateMode = "week";
                // 默认选中当前时间
                if (this.value == "" && conf.defaultValue) {
                    let curDate = dayjs();
                    curValue = curDate.year() + "-" + curDate.week();
                }
            } else if (conf.ctlType == 'quarter') {
                this.dateMode = "quarter";
                let curValue;
                // 默认选中当前时间
                if (this.value == "" && conf.defaultValue) {
                    let curDate = dayjs();
                    curValue = curDate.year() + "-" + curDate.format("Q");
                }
            }
            this.setCurValue(curValue);
        },
        isNumber(val) {
            return typeof val === 'number';
        },
        confirm(value) {
            if (value instanceof Object && value.hasOwnProperty("show")) {
                return;
            }
            if(this.isNumber(value)){
                value = JSON.stringify(value)
            }
            let conf = this.metadata.options;
            if (['week', 'quarter'].includes(conf.ctlType)) {
                let curValue;
                if (conf.ctlType == 'week') {
                    curValue = value[0].replace(" ", "-").replace(this.i18n('de','第'), "").replace(this.i18n('circumference','周'), "");
                } else if (conf.ctlType == 'quarter') {
                    curValue = value[0].replace(" ", "-")
                        .replace(this.i18n('one1','一'), "1")
                        .replace(this.i18n('two1','二'), "2")
                        .replace(this.i18n('three1','三'), "3")
                        .replace(this.i18n('wanton1','四'), "4").replace(this.i18n('quarter','季度'), "");
                }
                this.setData(curValue);
                return;
            }
            let date = dayjs(value).toDate();
            let Y = date.getFullYear() + "";
            let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
            let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
            let v = Y;
            if (conf.format.includes('/')) {
                if (['date', 'month'].includes(conf.ctlType)) {
                    v += "/" + M;
                }
                if (['date'].includes(conf.ctlType)) {
                    v += "/" + D;
                }
            } else {
                if (['date', 'month'].includes(conf.ctlType)) {
                    v += "-" + M;
                }
                if (['date'].includes(conf.ctlType)) {
                    v += "-" + D;
                }
            }
            if (this.params.hour) {
                let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
                v += " " + h;
            }
            if (this.params.minute) {
                let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
                v += ":" + m;
            }
            if (this.params.second) {
                let s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
                v += ":" + s;
            }
            this.setData(v);
        },
        setCurValue(val){
            if(!val){
                //默认
                this.defaultData={
                    year: "",
                    month: "",
                    startTime: "",
                    week: "",
                    quarter: ""
                }
                return;
            }
            if (["year"].includes(this.dateMode)) {
                this.defaultData.year = val;
            } else if (["year-month"].includes(this.dateMode)) {
                this.defaultData.month = val;
            } else if (["week"].includes(this.dateMode) && val) {
                let ary = val.split("-");
                this.defaultData.week = ary[0] + " 第" + ary[1] + "周";
            } else if (["quarter"].includes(this.dateMode) && val) {
                //2021-1
                let ary = val.split("-");
                this.defaultData.quarter = ary[0] + " " + ary[1]
                    .replace("1", this.i18n('one1','一'))
                    .replace("2", this.i18n('two1','二'))
                    .replace("3", this.i18n('three1','三'))
                    .replace("4", this.i18n('wanton1','四')) + this.i18n('quarter','季度');
            } else if (!["year", "year-month", "quarter"].includes(this.dateMode)) {
                if(Util.isUnixTimestampString(val)){
                    val = dayjs(Number(val));
                    //将时间戳数据改为YYYY-MM-DD格式的字符串数据
                    let conf = this.metadata.options;
                    let format = conf.format;
                    this.updateValue(val.format(format));
                }
                this.defaultData.startTime = val;
            }
        },
        onAllowClear(){
            this.setData('');
        }
    },
    watch: {
        value: function (val, oldVal) {
            this.setCurValue(val);
        },
    }
}
</script>

<style scoped>
.rx-date-select{
    border-radius: 5px;
    border: 0.03rem solid rgba(232, 232, 232, 1);
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding: 0.5rem 0.5rem;
}
.rx-date-name{
    flex: 1;
    margin-right: 0.5rem;
}
.rx-disabled{
    background: rgba(245, 246, 249, 1);
    display: flex;
    align-items: center;
    padding: 0.5rem;
    border-radius: 4px;
    border: none;
    min-height: 1rem;
}
.rx-date-icon{
    font-size: 0.9rem;
    color: rgba(0, 0, 0, 0.2);
}
</style>
